package com.ruike.alisurface.service;

import android.app.IntentService;
import android.content.Intent;

import com.ruike.alisurface.Constant;
import com.ruike.alisurface.bean.AdvBean;
import com.ruike.alisurface.serialport.MsgEventBus;
import com.ruike.alisurface.utils.FinalDbUtils;
import com.voodoo.lib_http.ApiTools;
import com.voodoo.lib_http.DownloadListener;
import com.voodoo.lib_logcat.L;
import com.voodoo.lib_utils.FileUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 广告图片下载类
 */
public class MyFileVideoService extends IntentService implements DownloadListener {

    public MyFileVideoService() {
        super("MyFileVideoService");
    }

    @Override
    public void onCreate() {
        super.onCreate();

    }

    List<String> urlList;
    List<String> urlpath = new ArrayList<>();

    @Override
    protected void onHandleIntent(Intent intent) {
        strpicList.clear();
        urllist.clear();
        mCount = 0;
        list.clear();
        try {
            urlList = intent.getStringArrayListExtra("urlList");
            assert urlList != null;
            L.i("-----downImgFile-开始解析数据--urlList-" + urlList.toString());
            showImgList();
        } catch (Exception e) {
            L.i("-----downImgFile-Exception-- " + e.toString());
        }
    }


    List<String> strpicList = new ArrayList<>();
    int mCount = 0;
    List<String> urllist = new ArrayList<>();
    String filepath = Constant.FilePath.ADV_VIDEO_FOLDER_PATH;
    List<String> list = new ArrayList<>();
    boolean isImgNext = true;

    /**
     * 下载
     */
    public void showImgList() {
        try {
            for (int intI = 0; intI < urlList.size(); intI++) {
                String p1 = urlList.get(intI);
                if (!p1.equals("") && p1 != null && !p1.equals("null")) {
                    if (!list.contains(p1)) {
                        list.add(p1);
                        String Name = p1.substring(p1.lastIndexOf("/")).substring(1);
                        strpicList.add(Name);
                    }
                }
                doVideodownload();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 进行图片的本地判断和下载
     */
    public void doVideodownload() {
        if (mCount >= list.size()) {
            L.i("-----downvdeioFile--1-下载视频 已经循环完了");
            setUpDataAdv();
            return;
        }
        isImgNext = true;
        for (int i = 0; i < list.size(); i++) {
            if (isImgNext) {
                File myFile = new File(filepath, strpicList.get(mCount));
                if (!myFile.exists()) {
                    isImgNext = false;
                    downImgFile(list.get(mCount), 1 + "");
                } else {
                    isImgNext = true;
                    delFile(strpicList);
                    urlpath.add(myFile.getAbsolutePath());
                }
                mCount++;
                if (mCount >= list.size()) {
                    L.i("-----downvdeioFile--2-下载视频 循环完了");
                    isImgNext = false;
                    setUpDataAdv();
                    return;
                }
            }
        }
    }


    //下载ship
    public void downImgFile(final String strNameList, String type) {
        try {
            L.i("-----downvdeioFile---下载视频");
            urllist.add(strNameList);
            String Name = strNameList.substring(strNameList.lastIndexOf("/")).substring(1);
            ApiTools.getInstance().getInstance().download(strNameList, filepath, Name, this);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void delFile(List<String> strpicList) {
        List<File> strlist = new ArrayList<>();
        strlist.clear();
        File[] folderFileList = FileUtils.getFolderFileList(filepath);
        L.i("tjf--delect--" + strpicList.toString());
        for (File file : folderFileList) {
            if (!strpicList.contains(file.getName())) {
                strlist.add(file);
            }
        }
        L.i("tjf--delect2222-" + strlist.toString());
        for (File file : strlist) {
            L.i(file.getName() + "-----删除文件---");
            if (file.exists()) {
                file.delete();
            }
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

    }


    @Override
    public void onDownloadStart(String url, int id) {

    }

    @Override
    public void onDownloading(String url, long progress, long total, int id) {
        if (progress == 100) {
            L.i("下载视频-   " + url + "===" + total + "==" + progress);
        }
    }

    @Override
    public void onDownloadComplete(String url, int id) {

    }

    @Override
    public void onDownloadSuccess(String url, File downloadFile, int id) {
        if (urllist.contains(url)) {
            L.i(mCount + "----下载视频成功 ----" + downloadFile.getAbsolutePath());
            delFile(strpicList);
            urlpath.add(downloadFile.getAbsolutePath());
            doVideodownload();
        }
    }

    @Override
    public void onDownloadFail(String url, String errorMsg, int id) {
        L.i(mCount + "---视频下载失败-Exception-requestUrl--" + url
                + "======" + errorMsg);
        doVideodownload();
    }

    public void setUpDataAdv() {
        FinalDbUtils.getInstance().deleteByWhere(AdvBean.class, " isImage = 1");
        for (int i = 0; i < urlpath.size(); i++) {
            AdvBean ab = new AdvBean(urlpath.get(i), "", 1);
            FinalDbUtils.getInstance().save(ab);
        }
        EventBus.getDefault().post(new MsgEventBus("adv_type", "视频样式"));
    }
}